package com.lagou.cluster.filter;

import com.lagou.cluster.constants.SystemConstants;
import com.lagou.cluster.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @ProjectName: S2-2
 * @Title: SessionInterceptor
 * @Package: com.lagou.cluster.filter
 * @Description: Session拦截
 * @author: Ian
 * @date: 2021-04-01 16:37
 * @version: V1.0.0
 */
public class SessionInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

        HttpSession session = request.getSession();
        if (session.getAttribute(SystemConstants.SESSION_ID) != null) {
            User userInfo = (User) redisTemplate.opsForValue().get(SystemConstants.AUTH_TOKEN + session.getAttribute(SystemConstants.SESSION_ID));
            if (userInfo != null) {
                return true;
            }
        }

        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().print("Unauthorized!");

        return false;

    }
}
